package org.budo.dubbo.protocol.async.repository.aliyun.mns;

import org.budo.dubbo.protocol.async.repository.AbstractAsyncRepository;
import org.budo.dubbo.protocol.async.repository.BudoAsyncInvocation;

import com.alibaba.dubbo.rpc.Invoker;
import com.alibaba.dubbo.rpc.RpcInvocation;
import com.aliyun.mns.client.CloudQueue;
import com.aliyun.mns.model.Message;

/**
 * 服务提供端拉取消息的回调，收到消息后执行对应的本地方法
 * 
 * @author lmw
 */
public class PopCallback extends AbstractListMessageAsyncCallback {
    private Invoker<?> invoker;
    private AbstractAsyncRepository asyncRepository;

    public PopCallback(CloudQueue cloudQueue, Invoker<?> invoker, AbstractAsyncRepository asyncRepository) {
        this.setCloudQueue(cloudQueue);
        this.invoker = invoker;
        this.asyncRepository = asyncRepository;
    }

    protected Object processMessage(Message message) throws Throwable {
        byte[] messageBody = message.getMessageBodyAsBytes();
        BudoAsyncInvocation asyncInvocation = this.asyncRepository.deserializeAsyncInvocation(messageBody, this.invoker);
        RpcInvocation dubboInvocation = BudoAsyncInvocation.toDubboInvocation(asyncInvocation);

        return invoker.invoke(dubboInvocation);
    }

    @Override
    public String toString() {
        return super.toString() + ", invoker=" + this.invoker;
    }
}